#include "cart_module.h"
#include <iostream>

namespace TakeAwayPlatform
{
    CartModule::CartModule(DatabaseHandler& dbHandler) : dbHandler(dbHandler) {}

    //添加进购物车
    bool CartModule::addItemToCart(int user_id, int dish_id, int quantity)
    {
        std::string sql = "INSERT INTO cart_items (user_id, dish_id, quantity) VALUES (" +
                          std::to_string(user_id) + ", " + std::to_string(dish_id) + ", " + std::to_string(quantity) +
                          ") ON DUPLICATE KEY UPDATE quantity = quantity + " + std::to_string(quantity);
        return dbHandler.update(sql);
    }

    //从购物车中删除
    bool CartModule::removeItemFromCart(int user_id, int dish_id)
    {
        std::string sql = "DELETE FROM cart_items WHERE user_id = " + std::to_string(user_id) + " AND dish_id = " + std::to_string(dish_id);
        return dbHandler.update(sql);
    }

    //更新购物车
    bool CartModule::updateItemQuantityInCart(int user_id, int dish_id, int quantity)
    {
        std::string sql = "UPDATE cart_items SET quantity = " + std::to_string(quantity) +
                        " WHERE user_id = " + std::to_string(user_id) + " AND dish_id = " + std::to_string(dish_id);
        return dbHandler.update(sql);
    }

    //得到购物车中包含的物品
    bool CartModule::getCartItems(int user_id, std::vector<std::pair<int, int>>& cart_items)
    {
        std::string sql = "SELECT dish_id, quantity FROM cart_items WHERE user_id = " + std::to_string(user_id);
        Json::Value result = dbHandler.query(sql);

        for (const auto& row : result)
        {
            cart_items.push_back({row["dish_id"].asInt(), row["quantity"].asInt()});
        }

        return !cart_items.empty();
    }

    //清空整个购物车
    bool CartModule::clearCart(int user_id)
    {
        std::string sql = "DELETE FROM cart_items WHERE user_id = " + std::to_string(user_id);
        return dbHandler.update(sql);
    }
}